package com.nord.Registration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.nord.R;
import com.nord.EventList.EventList;
import com.nord.EventList.Location;
import com.nord.Menus.Menus;
import com.nord.WebTools.HtmlBrowser;

public class Registration extends Activity {
	Button skraning, stadsetning, regBanner, aukaSkraning;
	TextView countdown, regTitle, regSaetaFjoldi, regLausSaeti, regBidlisti;
	List<HashMap<String, String>> users;
	List<HashMap<String, String>> eventList;
	String eventname = "";
	String username = "";
	ListView listView;
	int eventListIndex = 0;

	private boolean extra = false;
	String[] from = { "regNumber", "regUsername", "regExtra" };
	int[] to = {R.id.regListData};

	@Override
	public void onResume() {
		super.onResume();
		setContentView(R.layout.activity_registration);

		eventname = getIntent().getExtras().getString("EVENTNAME");
		username = getIntent().getExtras().getString("USERNAME");
		countdown = (TextView) findViewById(R.id.regTime);
		regSaetaFjoldi = (TextView) findViewById(R.id.regSaetaFjoldi);
		regLausSaeti = (TextView) findViewById(R.id.regLausSaeti);
		regBidlisti = (TextView) findViewById(R.id.regBidlisti);
		regTitle = (TextView) findViewById(R.id.regTitle);
		regTitle.setText(eventname);
		eventList = new ArrayList<HashMap<String,String>>();
		
		skraning = (Button) findViewById(R.id.regSkraning);
		stadsetning = (Button) findViewById(R.id.regStadsetning);
		aukaSkraning = (Button) findViewById(R.id.regAukaSkraning);

		aukaSkraning.setText("Skrá í Rútu");
		regBanner = (Button) findViewById(R.id.regBanner);

		Typeface tf = Typeface.createFromAsset(getAssets(), "DaysOne-Regular.ttf");
		regBanner.setTypeface(tf);

		listView = (ListView) findViewById(R.id.regSkraningarListi);
		new ExtractInformation().execute();

		if (skraning.isEnabled()) {
			skraning.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (skraning.getText().toString().matches(("Skrá mig"))) {
						new Request(true).execute();
					} else {
						final AlertDialog dialog = new AlertDialog.Builder(
								Registration.this).create();
						dialog.setTitle("Úrskráning úr\n"
								+ getIntent().getExtras()
										.getString("EVENTNAME"));
						dialog.setMessage("Ertu viss að þú vilt skrá þig úr "
								+ getIntent().getExtras()
										.getString("EVENTNAME") + " ?");

						dialog.setButton2("Nyet",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});

						dialog.setButton("Já",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										new Request(false).execute();
									}
								});

						dialog.show();
					}
				}
			});
		}

		if (aukaSkraning.isEnabled()) {
			aukaSkraning.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!extra) {
						new ExtraRegister("í", false).execute();
					} else {
						new ExtraRegister("úr", true).execute();
					}
				}

			});
		}

		stadsetning.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent maps = new Intent(Registration.this, Location.class);
				maps.putExtra("EVENTNAME", eventname);
				maps.putExtra("USERNAME",getIntent().getExtras().getString("USERNAME"));
				maps.putExtra("LOCATION", getIntent().getExtras().getString("LOCATION"));
				startActivity(maps);
			}
		});
	}

	private class ExtraRegister extends AsyncTask<Void, Integer, Void> {
		ProgressDialog progressBar;
		SimpleAdapter adapter;
		String ruta;
		boolean extra = false;

		public ExtraRegister(String ruta, boolean extra) {
			this.ruta = ruta;
			this.extra = extra;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(Registration.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að skrá " + ruta + "...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			if (!extra) {
				HtmlBrowser.getExecutor("https://www.nord.is/atburdir/"
						+ eventList.get(eventListIndex).get("id") + "/" 
						+ eventList.get(eventListIndex).get("slug") + "/"
						+ "skraning/auka/");
				extra = true;
			} else {
				HtmlBrowser.getExecutor("https://www.nord.is/atburdir/"
						+ eventList.get(eventListIndex).get("id") + "/" 
						+ eventList.get(eventListIndex).get("slug") + "/"
						+ "urskraning/auka/");
				extra = false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void status) {
			progressBar.dismiss();
			new ExtractInformation().execute();
		}
	}

	private class ExtractInformation extends AsyncTask<Void, Integer, String> {
		ProgressDialog progressBar;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(Registration.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að er að færa atburð ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}

		@Override
		protected String doInBackground(Void... params) {
			String[] htmlInfo = HtmlBrowser.getExecutor("http://www.nord.is/api/nord/events/?format=json&limit=10");
			String jsonString = htmlInfo[0];
			if(!jsonString.contains("Exception")){
				if (HtmlBrowser.cookieValidation(htmlInfo[1], Registration.this)) {
					eventList = HtmlBrowser.jsonEventProcessor(jsonString,htmlInfo[1], Registration.this);
					for(eventListIndex = 0;eventListIndex < eventList.size();eventListIndex++){
						if(eventList.get(eventListIndex).get("title").contains(eventname))
							break;
					}
					if(Long.parseLong(eventList.get(eventListIndex).get("start")) > 0){
						return "TIMER";
					}
					else if(Long.parseLong(eventList.get(eventListIndex).get("end")) > 0){
						users = HtmlBrowser.getUsersFromJSON(jsonString,eventList.get(eventListIndex).get("title"));
						return "OPEN";
					}
					users = HtmlBrowser.getUsersFromJSON(jsonString,eventList.get(eventListIndex).get("title"));
					return "CLOSED";
				
				} else{
					return "CookieException";
				}
			
			} else {
				return "404";
			}
		}

		@Override
		protected void onPostExecute(String status) {
			progressBar.dismiss();
			SimpleAdapter adapter;
			if (status.matches("TIMER")) {
				if (Integer.parseInt(eventList.get(eventListIndex).get("max")) > 0) {
					regSaetaFjoldi.setText("Sætafjöldi: " + Integer.parseInt(eventList.get(eventListIndex).get("max")));
					regLausSaeti.setText("Laus sæti: 0");
					regBidlisti.setText("Á biðlista: 0");
				} else {
					regSaetaFjoldi.setText("Engin fjöldatakmörkun");
					regLausSaeti.setVisibility(View.INVISIBLE);
					regBidlisti.setVisibility(View.INVISIBLE);
				}
				aukaSkraning.setVisibility(View.INVISIBLE);
				aukaSkraning.setEnabled(false);
				skraning.setEnabled(false);
				new CountDownTimer(Long.parseLong(eventList.get(eventListIndex).get("start")), 1000) {
					@Override
					public void onTick(long milliseconds) {
						int seconds = (int) (milliseconds / 1000) % 60;
						int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
						int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
						int days = (int) ((milliseconds / 86400000));

						countdown.setText(days + "d : " + hours + "h : " + minutes + "m : " + seconds + "s");
						countdown.setTextColor(Color.RED);
					}

					@Override
					public void onFinish() {
						countdown.setText("Skráning er hafin!");
						countdown.setTextColor(Color.parseColor("#4CC417"));
						skraning.setEnabled(true);
					}
				}.start();
			}
			else if (status.matches("OPEN")) {
				if (Integer.parseInt(eventList.get(eventListIndex).get("max")) > 0) {
					regSaetaFjoldi.setText("Sætafjöldi: " + Integer.parseInt(eventList.get(eventListIndex).get("max")));
					int seats = Integer.parseInt(eventList.get(eventListIndex).get("max")) - users.size();
					if(seats >= 0){
						regLausSaeti.setText("Laus sæti: " + seats); 
						regBidlisti.setText("Á biðlista: 0");
					} else {
						regLausSaeti.setText("Laus sæti: 0"); 
						regBidlisti.setText("Á biðlista: " + String.valueOf(-1 * seats));
					}
					
				} else {
					regSaetaFjoldi.setText("Engin fjölda-\ntakmörkun");
					regLausSaeti.setVisibility(View.INVISIBLE);
					regBidlisti.setVisibility(View.INVISIBLE);
				}
				countdown.setText("Skráning er hafin!");
				countdown.setTextColor(Color.parseColor("#4CC417"));
				
				skraning.setEnabled(true);
				skraning.setText("Skrá mig");
				
				aukaSkraning.setEnabled(false);
				aukaSkraning.setVisibility(View.INVISIBLE);
				
				for(int i = 0;i < users.size();i++){
					if(users.get(i).get("name").compareTo(username) == 0){
						skraning.setText("Hætta við skráningu");
						if(eventList.get(eventListIndex).get("checkbox").length() != 0){
							aukaSkraning.setEnabled(true);
							aukaSkraning.setVisibility(View.VISIBLE);
							if(users.get(i).get("checkbox") != null){
								extra = true;
								aukaSkraning.setText("Skrá mig úr " + users.get(i).get("checkbox"));
							} else {
								extra = false;
								aukaSkraning.setText("Skrá mig í " + eventList.get(eventListIndex).get("checkbox"));
							}
							
						} else {
							aukaSkraning.setEnabled(false);
							aukaSkraning.setVisibility(View.INVISIBLE);
						}
						break;
					} else {
						aukaSkraning.setEnabled(false);
						aukaSkraning.setVisibility(View.INVISIBLE);
						skraning.setText("Skrá mig");
						
					}
				}
				adapter = new RegistrationAdapter(Registration.this, users,
						R.layout.list_registration, from, to);
				listView.setAdapter(adapter);
			
			} else if (status.matches("CLOSED")) {
				countdown.setText("Skráning er búin");
				countdown.setTextColor(Color.RED);
				skraning.setEnabled(false);
				skraning.setText("Skrá mig");
				if (Integer.parseInt(eventList.get(eventListIndex).get("max")) > 0) {
					regSaetaFjoldi.setText("Sætafjöldi: " + Integer.parseInt(eventList.get(eventListIndex).get("max")));
					int seats = Integer.parseInt(eventList.get(eventListIndex).get("max")) - users.size();
					if(seats >= 0){
						regLausSaeti.setText("Laus sæti: " + seats); 
						regBidlisti.setText("Á biðlista: 0");
					} else {
						regLausSaeti.setText("Laus sæti: 0"); 
						regBidlisti.setText("Á biðlista: " + String.valueOf(-1 * seats));
					}
				} else {
					regSaetaFjoldi.setText("Engin fjölda-\ntakmörkun");
					regLausSaeti.setVisibility(View.INVISIBLE);
					regBidlisti.setVisibility(View.INVISIBLE);
				}
				countdown.setText("Skráning er Búin!\n Þú ert ekki á listanum!");
				countdown.setTextColor(Color.RED);
				for(int i = 0;i < users.size();i++){
					if(users.get(i).get("name").compareTo(username) == 0){
						countdown.setText("Skráning er Búin!\n Þú ert númer: " + users.get(i).get("position"));
						countdown.setTextColor(Color.parseColor("#4CC417"));
						skraning.setText("Hætta við skráningu");
						break;
					}
				}
				skraning.setEnabled(false);
				aukaSkraning.setEnabled(false);
				aukaSkraning.setVisibility(View.INVISIBLE);
				adapter = new RegistrationAdapter(Registration.this, users,
						R.layout.list_registration, from, to);
				listView.setAdapter(adapter);
			} else if (status.matches("CookieException")) {
				HtmlBrowser.expiredCookieHandler(Registration.this);
			} else {
				countdown.setText("Gat ekki tengst internetinu");
				countdown.setTextColor(Color.RED);
				skraning.setVisibility(View.INVISIBLE);
				aukaSkraning.setVisibility(View.INVISIBLE);
				regSaetaFjoldi.setVisibility(View.INVISIBLE);
				regLausSaeti.setVisibility(View.INVISIBLE);
				regBidlisti.setVisibility(View.INVISIBLE);
			}
			changeButtonColor();
		}
	}

	private class Request extends AsyncTask<Void, Void, Void> {
		ProgressDialog progressBar;
		SimpleAdapter adapter;
		boolean requestType = false;
		public Request(boolean requestType) {
		        super();
		        this.requestType = requestType;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(Registration.this);
			progressBar.setCancelable(true);
			if(requestType)
				progressBar.setMessage("Er að skrá þig í "+ getIntent().getExtras().getString("EVENTNAME") + "...");
			else
				progressBar.setMessage("Er að skrá þig úr "+ getIntent().getExtras().getString("EVENTNAME") + "...");

			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			if(requestType){
				String[] htmlInfo = HtmlBrowser.getExecutor("https://www.nord.is/atburdir/"
								+ eventList.get(eventListIndex).get("id") + "/" 
								+ eventList.get(eventListIndex).get("slug") + "/"
								+ "skraning/");
			} else {
				List<Cookie> cookies = ((AbstractHttpClient) HtmlBrowser.httpBrowser)
						.getCookieStore().getCookies();
				List<NameValuePair> info = new ArrayList<NameValuePair>(2);
				info.add(new BasicNameValuePair("confirmation-accept", "yes"));
				info.add(new BasicNameValuePair("csrfmiddlewaretoken", cookies.get(0).getValue()));
				HtmlBrowser.postExecutor("https://www.nord.is/atburdir/"
						+ eventList.get(eventListIndex).get("id") + "/" 
						+ eventList.get(eventListIndex).get("slug") + "/"
						+ "urskraning/", info);
				extra = false;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void status) {
			progressBar.dismiss();
			new ExtractInformation().execute();
		}
	}

	private void changeButtonColor() {
		if(skraning.getText().toString().matches("Skrá mig"))
			skraning.getBackground().setColorFilter(Color.GREEN,PorterDuff.Mode.MULTIPLY);
		else if(skraning.getText().toString().matches("Hætta við skráningu"))
			skraning.getBackground().setColorFilter(0xFFFF0000,PorterDuff.Mode.MULTIPLY);
	}
	
	@Override
	public void onBackPressed() {
		Intent eventlist = new Intent(Registration.this, EventList.class);
		eventlist.putExtra("USERNAME", getIntent().getExtras().getString("USERNAME"));
		startActivity(eventlist);
	}
}
